<?php

use Workerman\Worker;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;

require_once __DIR__ . '/vendor/autoload.php';

$log = new Logger("AlarmServer");
$stream = new StreamHandler('php://stdout', \Monolog\Logger::DEBUG);
$log->pushHandler($stream);
$camera_url = getenv('CAMERA_URL');
$bot = new PHPTelebot((!empty(getenv('TELEGRAM_BOT_APITOKEN'))) ? getenv('TELEGRAM_BOT_APITOKEN') : "BOT_API_TOKEN");
$ws_worker = new Worker('tcp://0.0.0.0:' . getenv('ALERT_PORT'));

$ws_worker->onConnect = function ($connection) use ($log) {
    $log->info("New connection");
};

// Emitted when data received
$ws_worker->onMessage = function ($connection, $data) use ($log, $camera_url) {
    $clear_data = mb_substr($data, 18);
    $log->debug("Got data: {$clear_data}");
    $payload = json_decode($clear_data);
    if (json_last_error() != JSON_ERROR_NONE) {
        $log->error("Error parsing JSON");
    } else {

        $channels = ['3'];

        if (in_array($payload->Channel, $channels) && $payload->Event == "MotionDetect" && $payload->Status == "Start" && $payload->Type == "Alarm") {
            $rand = rand(1111111, 9999999);
            Bot::sendPhoto("https://baz15-11-cam.smartintercom.ru/cam_view_6PlI8/{$rand}/webcapture.jpg", [
                'chat_id' => getenv('TELEGRAM_CHAT_ID'),
                'caption' => "Обнаружено движение на камере {$payload->SerialID}"
            ]);
        }
    }
};

$ws_worker->onClose = function ($connection) use ($log) {
    $log->info("Connection closed");
};

// Run worker
Worker::runAll();